package com.itheima.filter;

import com.itheima.util.CurrentHolder;
import com.itheima.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.util.ObjectUtils;

import java.io.IOException;


@Slf4j
//@Order(1)

//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {

    /**
     *
      * @param servletRequest:HttpServletRequest
     * @param servletResponse:HttpServletResponse
     * @param filterChain filterChain
     * @throws IOException IOException
     * @throws ServletException ServletException
     */

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest  request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;

        //1.获取请求url
        String url=request.getRequestURL().toString();

        //2.判断请求url中是否包含login，如果包含，说明是登录操作，放行
        if(url.contains("login")){//登录请求
           // log.info("登录请求，直接放行");
            filterChain.doFilter(request,response);
        return ;
        }

        //3.获取请求头中的令牌（token）
        String jwt=request.getHeader("token");

        //4.判断令牌是否存在，如果不存在，返回错误结果401，未登录
        if(ObjectUtils.isEmpty(jwt)|| JwtUtils.paraseJwt(jwt)==null){
            response.setStatus(401);
            return;
        }


        //5.如果token不为空，调用JwtUils工具类解析令牌jwt，如果解析失败响应401状态码
        try {
            Claims claims = (Claims) JwtUtils.paraseJwt(jwt);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);
            log.info("token解析成功，放行");

        } catch (Exception e) {
            log.info("tokend解析失败，响应401状态码");
            response.setStatus(401);
            return;
        }

        //6.校验通过，放行请求
        filterChain.doFilter(request,response);

        //7.清空当前线程绑定的ID
        CurrentHolder.remove();
    }
}
